package com.ruoyi.web.controller.system;

import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysCourt;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysCourtService;

/**
 * 法院信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/court")
public class SysCourtController extends BaseController
{
    @Autowired
    private ISysCourtService courtService;

    /**
     * 获取法院列表
     */
    @PreAuthorize("@ss.hasPermi('system:Court:list')")
    @GetMapping("/list")
    public AjaxResult list(SysCourt court)
    {
        List<SysCourt> Courts = courtService.selectCourtList(court);
        return AjaxResult.success(Courts);
    }

    /**
     * 查询法院列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:Court:list')")
    @GetMapping("/list/exclude/{courtId}")
    public AjaxResult excludeChild(@PathVariable(value = "courtId", required = false) Long courtId)
    {
        List<SysCourt> Courts = courtService.selectCourtList(new SysCourt());
        Iterator<SysCourt> it = Courts.iterator();
        while (it.hasNext())
        {
            SysCourt d = (SysCourt) it.next();
            if (d.getCourtId().intValue() == courtId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), courtId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(Courts);
    }

    /**
     * 根据法院编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:Court:query')")
    @GetMapping(value = "/{courtId}")
    public AjaxResult getInfo(@PathVariable Long courtId)
    {
        courtService.checkCourtDataScope(courtId);
        return AjaxResult.success(courtService.selectCourtById(courtId));
    }

    /**
     * 获取法院下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysCourt court)
    {
        List<SysCourt> courts = courtService.selectCourtList(court);
        return AjaxResult.success(courtService.buildCourtTreeSelect(courts));
    }

    /**
     * 加载对应角色法院列表树
     */
    @GetMapping(value = "/roleCourtTreeselect/{roleId}")
    public AjaxResult roleCourtTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysCourt> courts = courtService.selectCourtList(new SysCourt());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", courtService.selectCourtListByRoleId(roleId));
        ajax.put("courts", courtService.buildCourtTreeSelect(courts));
        return ajax;
    }

    /**
     * 新增法院
     */
    @PreAuthorize("@ss.hasPermi('system:Court:add')")
    @Log(title = "法院管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysCourt court)
    {
        if (UserConstants.NOT_UNIQUE.equals(courtService.checkCourtNameUnique(court)))
        {
            return AjaxResult.error("新增法院'" + court.getCourtName() + "'失败，法院名称已存在");
        }
        court.setCreateBy(getUsername());
        return toAjax(courtService.insertCourt(court));
    }

    /**
     * 修改法院
     */
    @PreAuthorize("@ss.hasPermi('system:Court:edit')")
    @Log(title = "法院管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysCourt court)
    {
        Long CourtId = court.getCourtId();
        courtService.checkCourtDataScope(CourtId);
        if (UserConstants.NOT_UNIQUE.equals(courtService.checkCourtNameUnique(court)))
        {
            return AjaxResult.error("修改法院'" + court.getCourtName() + "'失败，法院名称已存在");
        }
        else if (court.getParentId().equals(CourtId))
        {
            return AjaxResult.error("修改法院'" + court.getCourtName() + "'失败，上级法院不能是自己");
        }
        else if (StringUtils.equals(UserConstants.COURT_DISABLE, court.getStatus()) && courtService.selectNormalChildrenCourtById(CourtId) > 0)
        {
            return AjaxResult.error("该法院包含未停用的子法院！");
        }
        court.setUpdateBy(getUsername());
        return toAjax(courtService.updateCourt(court));
    }

    /**
     * 删除法院
     */
    @PreAuthorize("@ss.hasPermi('system:Court:remove')")
    @Log(title = "法院管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{courtId}")
    public AjaxResult remove(@PathVariable Long courtId)
    {
        if (courtService.hasChildByCourtId(courtId))
        {
            return AjaxResult.error("存在下级法院,不允许删除");
        }
        if (courtService.checkCourtExistUser(courtId))
        {
            return AjaxResult.error("法院存在用户,不允许删除");
        }
        courtService.checkCourtDataScope(courtId);
        return toAjax(courtService.deleteCourtById(courtId));
    }
}
